package org.Shiikong_Memory.SakuraBlockFrame.AutoPluginConfig;

import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic;
import javax.tools.FileObject;
import javax.tools.StandardLocation;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.util.Set;

@SupportedAnnotationTypes("org.Shiikong_Memory.SakuraBlockFrame.AutoPluginConfig.FrameworkPluginConfig")
@SupportedSourceVersion(SourceVersion.RELEASE_8)
public class FrameworkPluginConfigProcessor extends AbstractProcessor {
    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        System.out.println("开始自动生成plugin.yml配置文件");
        for (TypeElement annotation : annotations) {
            Set<? extends javax.lang.model.element.Element> annotatedElements = roundEnv.getElementsAnnotatedWith(annotation);
            for (javax.lang.model.element.Element element : annotatedElements) {
                FrameworkPluginConfig pluginConfig = element.getAnnotation(FrameworkPluginConfig.class);
                try {
                    FileObject fileObject = processingEnv.getFiler().createResource(StandardLocation.CLASS_OUTPUT, "", pluginConfig.configFileName());
                    try (Writer writer = new OutputStreamWriter(fileObject.openOutputStream(), StandardCharsets.UTF_8)) {
                        writer.write("name: " + pluginConfig.pluginName() + "\n");
                        writer.write("version: " + pluginConfig.version() + "\n");
                        writer.write("description: " + pluginConfig.description() + "\n");
                        writer.write("author: " + pluginConfig.author() + "\n");
                        String mainClass = element.toString().replace(" ", "");
                        writer.write("main: " + mainClass + "\n");
                        writer.write("commands:\n");
                        for (String command : pluginConfig.mainCommands()) {
                            writer.write("  " + command + ":\n");
                            writer.write("    description: 这个指令来自插件： " + pluginConfig.pluginName() + "\n");
                            writer.write("    usage: /<command>\n");
                        }
                    }
                } catch (IOException e) {
                    processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Error generating configuration file: " + e.getMessage());
                }
            }
        }
        System.out.println("plugin.yml配置文件生成成功");
        return true;
    }
}
